<?php
namespace app\interfaces\controller;

use app\interfaces\model\ShopGoodsEvaluate as ShopGoodsEvaluateModel;
use think\Request;
use think\Db;
use think\Cache;
use think\Exception;

class ShopGoodsEvaluate
{

    /*
     * 用户端 - 评论列表
     * @param  string $goods_id 商品ID
     * @param  string $type     状态
     */
    public function combo_list()
    {
        // 获取参数
        $goods_id = Request::instance()->param('goods_id');
        $grade = Request::instance()->param('grade', '');
        $img = Request::instance()->param('img');

        if (empty($goods_id)) throw new Exception('not Empty');

        $condition['status'] = ['eq', '1'];
        $condition['goods_id'] = ['eq', $goods_id];


        // 晒图
        if (!empty($img)) $condition['picArr'] = ['neq', ''];

        switch ($grade) {
            case $grade > '2':
                $condition['grade'] = ['gt', 2];
                break;
            case $grade == '2':
                $condition['grade'] = ['eq', 2];
                break;
            case $grade < '2':
                $condition['grade'] = ['lt', 2];
                break;
            default:
                $condition['grade'] = ['gt', '0'];
        }

        // 读取参数
        $result = Db::view('shop_goods_evaluate', 'content,grade,attr,picArr,status,create_time')
            ->view('member', 'nickname,avatar', 'member.id = shop_goods_evaluate.member_id','left')
            ->where($condition)
            ->order(['create_time' => 'desc'])
            ->paginate(6)
            ->toArray();
        // 闭包
        $data = array_map(function ($dispose) {
            if (is_array($dispose)) {
                foreach ($dispose as &$item) {
                    if(is_null($item['nickname'])) $item['nickname'] = '';
                    if(is_null($item['avatar'])) $item['avatar'] = '';
                    if (empty($item['picArr'])) {
                        $item['picArr'] = [];
                    } else {
                        $item['picArr'] = unserialize($item['picArr']);
                    }
                    $item['create_time'] = date('Y-m-d', $item['create_time']);
                }
            }
            return $dispose;
        }, $result);

        // 统计
        $statistics['all_count'] = ShopGoodsEvaluateModel::where(['goods_id' => $goods_id])->where(['status' => 1])->count();  // 全部
        $statistics['good_count'] = ShopGoodsEvaluateModel::where(['goods_id' => $goods_id, 'grade' => ['gt', '2']])->where(['status' => 1])->count();  // 好评
        $statistics['centre_count'] = ShopGoodsEvaluateModel::where(['goods_id' => $goods_id, 'grade' => '2'])->where(['status' => 1])->count();  // 中评
        $statistics['bad_count'] = ShopGoodsEvaluateModel::where(['goods_id' => $goods_id, 'grade' => ['lt', '2']])->where(['status' => 1])->count();  // 差评
        $statistics['img_count'] = ShopGoodsEvaluateModel::where(['goods_id' => $goods_id, 'picArr' => ['neq', '']])->where(['status' => 1])->count();  // 晒图

        return ['code' => 200, 'message' => '成功', 'data' => $data, 'statistics' => $statistics];
    }

    public function param(){
        $data = Request::instance()->param();
        return $data;
    }


    /*
     * 用户端 - 商品评价
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     * @param  string $goods_id         商品ID
     * @param  string $content          评论内容
     * @param  string $grade            星数
     * @param  string $attr             商品属性
     * @param  string $picArr           评论组图
     */
    public function goods_evaluate()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();
        // halt(request()->file());
        if (empty($data['user_id']) || empty($data['order_number']) || empty($data['goods_id']) || empty($data['content']) || empty($data['grade']) ) throw new Exception('not Empty');

        // 启动事务
//        Db::startTrans();
//        try {

            // 判断是否提交过
            $find = Db::name('member_order_attached')
                ->where(['goods_id' => $data['goods_id'],'shop_order_number' => $data['order_number'], 'status' => '1'])
                ->value('title');

            if (!empty($find)) return ['code' => 402, 'message' => '该商品已评价,请勿重复评价'];

            $information = [
                'member_id'   => $data['user_id'],
                'shop_id'     => 0,
                'goods_id'    => $data['goods_id'],
                'content'     => $data['content'],
                'grade'       => $data['grade'],
                'title'       => '',
                'attr'        => '',
                'thumb_img'   => '',
                'picArr'      => multi_upload(),
                'create_time' => time()
            ];

            // 添加到评论表
            Db::name('shop_goods_evaluate')->insert($information);

            // 更改信息
            Db::name('member_order_attached')
                ->where(['goods_id' => $data['goods_id'], 'shop_order_number' => $data['order_number'], 'status' => '2'])
                ->update(['status' => '1']);

            // 增长评论数
            Db::name('shop_goods')->where(['id' => $data['goods_id']])->setInc('evaluate_number');

            // 送积分
            //Db::name('member')->where(['id' => $data['user_id']])->setInc('integral', Cache::get('web_integral_evaluate_goods'));

            // 添加记录
//            Db::name('integral_record')->insert(
//                [
//                    'member_id'   => $data['user_id'],
//                    'type_id'     => '1',
//                    'type'        => '购买',
//                    'integral'    => Cache::get('web_integral_evaluate_goods'),
//                    'title'       => '评价商品' . $find,
//                    'create_time' => time()
//                ]
//            );

            // 查询是否还有
            $status = Db::name('member_order_attached')
                ->where(['shop_order_number' => $data['order_number'], 'status' => '2'])
                ->value('id');

            // 更改主表
            if (empty($status)) {
                Db::name('member_order')
                    ->where(['shop_order_number' => $data['order_number'], 'member_id' => $data['user_id']])
                    ->update(['status' => '4']);
                $goods_sum = db('member_order_attached')->where('shop_order_number',$data['order_number'])->sum('number');
                $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $data['user_id'],'title' => $data['order_number'],'content' => '您的订单完成,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
                db('mem_mess')->insert(['member_id' => $data['user_id'],'message_id' => $message_id,'create_time' => time(),'click' => 0]);
            }

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

//        } catch (\Exception $e) {
//
//            // 回滚事务
//            Db::rollback();
//
//            return ['code' => 401, 'message' => $e->getMessage(),'line' => $e->getLine()];
//        }

    }

}
